/**
 * 项目渠道单编辑权限
 */
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
export default {
  data() {
    return {
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  methods: {
    isEditAuth(item, projectItem = null) {
      // 项目状态为待提交或待初审 && [ 全向编辑(crm:projectChild:edit) ||  执行人  ||  销售  ||  创建人 ||  （  部门编辑权限crm:projectChild:departmentEdit  && 当前用户的部门是协作部门或所属部门 ）]
      if (!item) return false;
      const projectStatus = projectItem ? projectItem.projectStatus : item.projectStatus;
      if (!(projectStatus === 0 || projectStatus === 1)) {
        return false;
      }
      if (hasRouteAuth('crm:projectChild:edit')) return true; // 全向编辑
      // 当前登录的用户是否在该条订单的执行人中
      let haveOrderOperator = false;
      if (item.orderInfo.orderOperator && item.orderInfo.orderOperator.length) {
        haveOrderOperator = item.orderInfo.orderOperator.some(i => {
          return i.id === this.userInfo.id;
        });
      }

      // 是否是项目渠道单创建人
      let isCreate = false;
      if (item.orderInfo.createUserId) {
        isCreate = this.userInfo.id === item.orderInfo.createUserId;
      }

      // 是否是当前销售
      let haveOrderMarket = false;
      if (item.clientInfo.marketId) {
        haveOrderMarket = this.userInfo.id === item.clientInfo.marketId;
      }
      // 如果拥有部门编辑权限，则判断协作部门和所属部门
      const departmentId = item.orderInfo.attributionMatrix; // 所属部门
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;
      let departmentAuth = false;
      if (hasRouteAuth('crm:projectChild:departmentEdit') || isNoOperator) {
        let cooperationDepartmentIds = []; // 协作部门ID
        if (item.orderInfo.cooperationDepartment && item.orderInfo.cooperationDepartment.length) {
          cooperationDepartmentIds = item.orderInfo.cooperationDepartment.map(i => i.id);
        }
        const currentDeptIds = this.userInfo.currentDeptIds || []; // 当前部门的所有id，比如：用户部门是 研发部->产品组，那么当前部门就是产品组
        const topDeptIds = this.userInfo.topDeptIds || []; // 顶级部门的id列表，比如：用户部门是 研发部->产品组，那么顶级部门就是研发部
        const departmentAry = currentDeptIds.concat(topDeptIds);
        departmentAuth = departmentAry.some(i => {
          return (i === departmentId) || cooperationDepartmentIds.includes(i);
        });
      }
      return isCreate || haveOrderOperator || haveOrderMarket || departmentAuth;
    }
  }
};
